import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/placeholder/appbar_base.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/pages/other/local/AlbumImageListPage.dart';
import 'package:wallpaper/providers/setting_provider.dart';
import 'package:wallpaper/tools/route_animation.dart';

class AlbumListPage extends StatefulWidget {
  const AlbumListPage({super.key});

  @override
  _AlbumListPageState createState() => _AlbumListPageState();
}

class _AlbumListPageState extends State<AlbumListPage> {
  final ScrollController _albumScrollController = ScrollController();
  final List<AssetPathEntity> _albumList = [];
  final Map<String, Uint8List> _albumCoverCache = {};
  bool _hasPermission = false;

  @override
  void initState() {
    super.initState();
    _requestPermissionAndLoadAlbums();
  }

  @override
  void dispose() {
    _albumScrollController.dispose();
    super.dispose();
  }

  /// 请求权限并加载相册
  Future<void> _requestPermissionAndLoadAlbums() async {
    final authState = await PhotoManager.requestPermissionExtend();
    if (authState.isAuth) {
      setState(() => _hasPermission = true);
      final allAlbums = await PhotoManager.getAssetPathList(
        type: RequestType.image,
        filterOption: FilterOptionGroup(
          imageOption:
              const FilterOption(sizeConstraint: SizeConstraint(minWidth: 1)),
        ),
      );

      // 定义英文相册名到中文的映射
      final Map<String, String> albumNameMap = {
        // 基础相册
        'Camera': '相机',
        'Screenshot': '截图',
        'Download': '下载',
        'Pictures': '图片',
        'Videos': '视频',

        // 系统常用分类
        'Recent': '最近',
        'All photos': '所有照片',
        'Favorites': '收藏',
        'Edited': '已编辑',

        // 应用相关
        'Apps': '应用',
        'WhatsApp Images': 'WhatsApp 图片',
        'WeChat Images': '微信图片',
        'QQ Images': 'QQ 图片',

        // 其他常见目录
        'DCIM': '相机胶卷',
        'Movies': '影片',
        'Documents': '文档',
        'Screenshots': '截图', // 兼容部分设备的复数形式
        'Downloads': '下载', // 兼容部分设备的复数形式
        'appicon': '应用图标',
      };
      // 处理相册名称并排序
      for (var album in allAlbums) {
        // 如果有对应的中文名称则替换，否则保持原名
        final chineseName = albumNameMap[album.name] ?? album.name;
        // 创建新的AssetPathEntity副本（注意：实际项目中可能需要更合适的方式）
        final renamedAlbum = album.copyWith(name: chineseName);
        _albumList.add(renamedAlbum);
      }

      _albumList.sort((a, b) => a.name.compareTo(b.name));
      _preloadAlbumCovers(_albumList);
    } else {
      setState(() => _hasPermission = false);
    }
  }

  /// 预加载相册首图
  Future<void> _preloadAlbumCovers(List<AssetPathEntity> albums) async {
    for (final album in albums) {
      try {
        final firstAsset = await _getAlbumFirstImage(album);
        if (firstAsset != null) {
          final coverBytes = await _compressAlbumCover(firstAsset);
          if (coverBytes != null) {
            setState(() => _albumCoverCache[album.id] = coverBytes);
          }
        }
      } catch (e) {
        debugPrint('加载相册${album.name}首图失败: $e');
      }
    }
  }

  /// 获取相册第一张图
  Future<AssetEntity?> _getAlbumFirstImage(AssetPathEntity album) async {
    final assets = await album.getAssetListRange(start: 0, end: 1);
    return assets.isNotEmpty ? assets.first : null;
  }

  /// 压缩相册首图
  Future<Uint8List?> _compressAlbumCover(AssetEntity asset) async {
    final file = await asset.file;
    if (file == null) return null;
    return FlutterImageCompress.compressWithFile(
      file.path,
      minHeight: 200,
      minWidth: 300,
      quality: 80,
      autoCorrectionAngle: true,
    );
  }

  /// 构建相册项
  Widget _buildAlbumItem(AssetPathEntity album, ColorScheme theme) {
    final hasCover = _albumCoverCache.containsKey(album.id);
    return GestureDetector(
      // 点击相册跳转图片列表页
      onTap: () => RouteAnimation().animateRoute(
        context,
        AlbumImageListPage(album: album),
        type: AnimationType.fade,
      ),
      child: Container(
        decoration: BoxDecoration(
          color: theme.surfaceVariant.withOpacity(0.5),
          boxShadow: [
            BoxShadow(
                color: Colors.grey.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2)),
          ],
        ),
        child: Stack(fit: StackFit.expand, children: [
          // 相册首图背景
          if (hasCover)
            Image.memory(_albumCoverCache[album.id]!, fit: BoxFit.cover)
          else
            Container(
              color: theme.surface,
              child: Icon(Icons.photo_library_outlined,
                  color: theme.onSurface.withOpacity(0.3), size: 40),
            ),
          // 渐变遮罩
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Colors.black.withOpacity(0.6),
                  Colors.black.withOpacity(0.2)
                ],
                begin: Alignment.bottomCenter,
                end: Alignment.topCenter,
              ),
            ),
          ),
          // 相册名称和数量
          Padding(
            padding: const EdgeInsets.all(4),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    album.name,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                      shadows: [Shadow(blurRadius: 2, color: Colors.black54)],
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  FutureBuilder<int>(
                    future: album.assetCountAsync,
                    builder: (context, snapshot) => Text(
                      '${snapshot.data ?? 0} 张图片',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.9),
                        fontSize: 11,
                        shadows: [Shadow(blurRadius: 2, color: Colors.black54)],
                      ),
                    ),
                  ),
                ]),
          ),
        ]),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final SettingProvider setting = Provider.of<SettingProvider>(context);
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppbarBase(title: '本地相册'),
      body: _buildBody(setting, theme),
    );
  }

  /// 构建页面主体
  Widget _buildBody(SettingProvider setting, ColorScheme theme) {
    if (!_hasPermission) {
      return Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          const Icon(Icons.perm_media_outlined, size: 60, color: Colors.grey),
          const SizedBox(height: 16),
          Text("需要相册权限才能查看",
              style: TextStyle(color: theme.onSurface.withOpacity(0.7))),
          const SizedBox(height: 16),
          ElevatedButton(
              onPressed: PhotoManager.openSetting, child: const Text("打开设置")),
        ]),
      );
    }

    if (_albumList.isEmpty) return const Empty();

    return Padding(
      padding: const EdgeInsets.all(4),
      child: GridView.builder(
        controller: _albumScrollController,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: OptionsBase().imageColumns(context) + 1,
          childAspectRatio: 1,
          mainAxisSpacing: 4,
          crossAxisSpacing: 4,
        ),
        itemCount: _albumList.length,
        itemBuilder: (context, index) =>
            _buildAlbumItem(_albumList[index], theme),
      ),
    );
  }
}
